﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Collections;

namespace Proggy.Sandbox.QueryAdConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            // http://stackoverflow.com/questions/4249139/c-sharp-active-directory-get-domain-name-of-user
            // http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C
            // http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/ecb16a63-6619-4c68-a77c-8bb2682fc1be
            // http://msdn.microsoft.com/en-us/library/windows/desktop/aa746475(v=vs.85).aspx

            // get current domain
            var domain = Domain.GetCurrentDomain();

            // print
            Console.WriteLine("The current domain is {0}",domain);

            // NOT USED
            //var context = new DirectoryContext(DirectoryContextType.Domain, domain.ToString());

            // NOT USED
            //var theDomain = Domain.GetDomain(context);

            // get context
            var principalContext = new PrincipalContext(ContextType.Domain, domain.ToString());

            // get group context
            var groupPrincipal = GroupPrincipal.FindByIdentity(principalContext, "Domain Users");

            // get all members of group
            var members = groupPrincipal.GetMembers(false);//.ToList();

            // get me
            var randomUser = members.Single(x => x.SamAccountName.ToUpper() == "RJOHNSON");

            // print
            Console.WriteLine("{0} is the random user\n\nPROPERTIES...\n\n", randomUser.DisplayName);

            // get root entry for domain
            var rootEntry = domain.GetDirectoryEntry();

            // get searcher
            using (var searcher = new DirectorySearcher(rootEntry))
            {

                searcher.Filter = "(cn=" + randomUser.SamAccountName + ")";


                var result = searcher.FindOne();


                var props = result.Properties;

                foreach (DictionaryEntry propt in props) {

                    var key = propt.Key.ToString();
                    var val = ((ResultPropertyValueCollection)propt.Value)[0].ToString();

                    Console.WriteLine("{0} = {1}", key,val);
                }


            }

            // dispose            
            rootEntry.Dispose();
            randomUser.Dispose();
            members.Dispose();
            groupPrincipal.Dispose();
            principalContext.Dispose();
            domain.Dispose();



            //}

            Console.ReadKey();
        }
    }
}
